/**
 * Created by Administrator on 2019-01-21.
 */
import axios from 'axios'
// import qs from 'qs'
// import { Toast } from 'vant'
// import router from '../router'
// import md5 from 'js-md5'

axios.defaults.timeout = 50000;//响应时间
axios.defaults.headers = {
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  // versionCode:25
};
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
 
  return config;
}, (error) => {

  return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use(
  (response) => {
    //对响应数据做些事
    if (response.status === 200) {
      return Promise.resolve(response.data);
    } else {

      return Promise.resolve(response.data);
    }
    // return response;
  }, (error) => {

    if (error.response.status) {
      // console.log(error.response.status)
      switch (error.response.status) {
        //未登录
        case 401:
          // Toast('401')
          break
        case 403:
          // Toast('403')
          break
        case 404:
          // Toast('404');
          break
        default:
          // Toast('error')
      }
    }
    return Promise.reject(error);
  });

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {
        resolve(response);
      }, err => {
        reject(err);
      })
      .catch((error) => {
        reject(error)
      })
  })
}

////返回一个Promise(发送get请求)
export function fetchGet(url, param) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: param })
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function param(data) {
  let url = ''
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : ''
    url += '&' + k + '=' + encodeURIComponent(value)
  }
  return url ? url.substring(1) : ''
}

export default {
  fetchPost,
  fetchGet,
}
